package com.pal.common.server;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 即时通讯
 * @Author: 刘世铭
 * @Date 2022/7/18 16:52
 */
@Component //创建IOC 对象
@Scope(scopeName = "prototype")  //设置IOC 创建对象的方式  为多模式
@ServerEndpoint("/server/chat/{nickname}")
public class WebSocketServer {
    //记录当前在线的所有用户   Key   用户昵称   value：会话对象
    public static ConcurrentHashMap<String, Session> map = new ConcurrentHashMap<>();
    private String name;
    //创建连接
    @OnOpen
    public void open(Session session, @PathParam("nickname") String name){
        //1.验证昵称是否存在
        if (map.containsKey(name)) {
            //昵称重复， 返回消息
            try {
                session.getBasicRemote().sendText("亲，你的昵称已经被暂用了！！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            //添加在线用户
            map.put(name,session);
            this.name=name;
            //群发信息   欢迎语
            sendMoreMsg("欢迎"+name+"进入到聊天室");
        }
        System.err.println("新用户连接");
    }
    //接收消息
    @OnMessage
    public void receive(String msg){
        sendMoreMsg(name+"说："+msg);
        System.out.println("接收消息："+msg);
    }
    //出现错误
    @OnError
    public void error(Session session,Throwable throwable){
        System.out.println("错误："+throwable.getMessage());

    }
    //断开连接
    @OnClose
    public void close(){
        //退出聊天
        map.remove(name);
        sendMoreMsg(name+"退出勒聊天室！！");
        System.err.println("关闭");

    }

    public static void sendMoreMsg(String msg){
        //接收消息   转发消息
        for (String b : map.keySet()) {
            try {
                map.get(b).getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
